<template>
  <a-modal
    width="60%"
    v-model="modal2Visible"
    :title="title"
    centered
    @ok="onSubmit"
  >
    <a-spin tip="Loading..." :spinning="spin">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="计划名称" prop="planName">
              <a-input placeholder="请选择计划名称" v-model="form.planName"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="执行顺序" prop="irrigationOrder">
              <a-select disabled @change="sequenceBtn" v-model="form.irrigationOrder" placeholder="请选择执行顺序">
                <a-select-option value="0">依次执行</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="是否联动泵" prop="systemName">
              <a-select v-model="form.systemName" placeholder="请选择是否联动泵">
                <a-select-option value="0">不绑定</a-select-option>
                <a-select-option value="1">1号系统</a-select-option>
                <a-select-option value="2">2号系统</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="sequence==0">
            <a-form-model-item label="工作日期" prop="workDay">
              <!--              <a-select v-model="form.workDay" placeholder="请选择工作日期">-->
              <!--                <a-select-option value="1">第一天</a-select-option>-->
              <!--                <a-select-option value="2">第二天</a-select-option>-->
              <!--                <a-select-option value="3">第三天</a-select-option>-->
              <!--                <a-select-option value="4">第四天</a-select-option>-->
              <!--                <a-select-option value="5">第五天</a-select-option>-->
              <!--                <a-select-option value="6">第六天</a-select-option>-->
              <!--                <a-select-option value="7">第七天</a-select-option>-->
              <!--                <a-select-option value="8">第八天</a-select-option>-->
              <!--                <a-select-option value="9">第九天</a-select-option>-->
              <!--                <a-select-option value="10">第十天</a-select-option>-->
              <!--              </a-select>-->
              <a-input-search v-model="form.workDay" placeholder="请输入工作日期">
                <a-button slot="enterButton">
                  天
                </a-button>
              </a-input-search>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="sequence!=0">
            <a-form-model-item label="灌溉时长" prop="irrigationTime">
              <a-select v-model="form.irrigationTime" placeholder="请选择间隔时长">
                <a-select-option value="1">1小时</a-select-option>
                <a-select-option value="2">2小时</a-select-option>
                <a-select-option value="3">3小时</a-select-option>
                <a-select-option value="4">4小时</a-select-option>
                <a-select-option value="5">5小时</a-select-option>
                <a-select-option value="6">6小时</a-select-option>
                <a-select-option value="7">7小时</a-select-option>
                <a-select-option value="8">8小时</a-select-option>
                <a-select-option value="9">9小时</a-select-option>
                <a-select-option value="10">10小时</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="开阀时间" prop="startDate">
              <a-date-picker
                show-time
                v-model="form.startDate"
                placeholder="请选择开阀时间"
                style="width: 100%;"
                @change="startOnChange"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="sequence==0">
            <a-form-model-item label="每组灌溉" prop="irrigationTime">
              <a-input-search style="width: 48%;margin-right: 4%" @change="startEnd" v-model="intervalDurationL"
                              placeholder="请输入每组灌溉">
                <a-button slot="enterButton">
                  小时
                </a-button>
              </a-input-search>
              <a-input-search style="width: 48%" @change="startEnd" v-model="intervalDurationR"
                              placeholder="请输入每组灌溉">
                <a-button slot="enterButton">
                  分钟
                </a-button>
              </a-input-search>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="轮灌组" prop="groupIds">
              <a-select
                v-model="group"
                mode="multiple"
                style="width: 100%"
                placeholder="请选择轮灌组"
                @change="handleChange"
                @deselect="delSelect"
                option-label-prop="label"
              >
                <a-select-option v-for="(item,index) in irrigationGroups" :label="item.name" key="index"
                                 :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>

            </a-form-model-item>
          </a-col>
          <!--          v-if="title == '新增灌溉计划'"-->
          <a-col :span="24">
            <a-table :columns="columns" row-key="id" :data-source="TableList" bordered>
              <span slot="deviceList" slot-scope="text, record">
                      {{ record.deviceNames }}
                 </span>
              <span slot="remarks" slot-scope="text, record">
                      {{ record.remarks == 'NaN-NaN-NaN NaN:NaN:NaN' ? '' : record.remarks }}
                 </span>
              <span slot="sysOrgCode" slot-scope="text, record">
                {{ record.reserveTwo == 'NaN-NaN-NaN NaN:NaN:NaN' ? '' : record.reserveTwo }}
              </span>
            </a-table>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>
<script>
import moment from 'moment';

import {add, edit, editList, queryIrrigationGroupByMainId, editStatus} from '@/api/plan'
import {irrigationGroupLists} from '@/api/meteorological'

export default {
  data() {
    return {
      value: ['111', 'usa'],
      id: '', // 编辑id
      group: [],  // 轮灌组绑定
      sequence: 0,
      title: '新增灌溉计划',
      TableList: [],
      columns: [
        {
          title: '灌溉组名称',
          dataIndex: 'name',
          width: 120,
        },
        {
          title: '阀门',
          scopedSlots: {customRender: 'deviceList'},
        },
        {
          title: '阀门开启时间',
          dataIndex: 'remarks',
          scopedSlots: {customRender: 'remarks'},
          width: 180,
        },
        {
          title: '阀门关闭时间',
          dataIndex: 'sysOrgCode',
          scopedSlots: {customRender: 'sysOrgCode'},
          width: 180,
        }
      ],
      modal2Visible: false,
      labelCol: {span: 6},
      wrapperCol: {span: 14},
      other: '',
      spin: true,
      intervalDurationL: 0,
      intervalDurationR: 0,
      form: {
        planName: '', //计划名称
        irrigationOrder: '0', // 轮循方式
        // irrigationTime: undefined, // 灌溉时长
        irrigationTime: 0, //每组灌溉
        startDate: '', //开始时间
        groupIds: [], // 轮灌组
        planType: '1', //轮播周期
        createTime: '', // 开始时间
        systemName: undefined,//所属系统
        workDay: undefined,//工作日期
      },
      timeLeft: '', // 计算时间
      timeRight: '', // 计算时间
      irrigationGroups: [],
      defaultOption: [],
      listDel: [],
      editLists: [],
      rules: {
        planName: [{required: true, message: '请输入轮灌组名称', trigger: 'blur'}],
        irrigationOrder: [{required: true, message: '请选择执行顺序', trigger: 'blur'}],
        irrigationTime: [{required: true, message: '请选择灌溉时长', trigger: 'blur'}],
        intervalDuration: [{required: true, message: '请选择每组灌溉', trigger: 'change'}],
        startDate: [{required: true, message: '请选择开阀时间', trigger: 'change'}],
        groupIds: [{required: true, message: '请选择轮灌组', trigger: 'change'}],
        systemName: [{required: true, message: '请选择所属系统', trigger: 'blur'}],
        workDay: [{required: true, message: '请选择工作日期', trigger: 'blur'}],
      }
    }
  },
  methods: {
    // 阀门开启时间 阀门关闭时间
    startEnd() {
      function time(a, b) {
        var nd = new Date(Date.parse(a.replace(/-/g, "-"))); //改为标准格式：2016/04/05 09:29:15
        nd = nd.valueOf(); //转换为毫秒数
        nd = nd + Number(b)
        nd = new Date(nd);
        var y = nd.getFullYear();
        var m = nd.getMonth() + 1;
        var d = nd.getDate();
        var hh = nd.getHours();
        var mm = nd.getMinutes();
        var ss = nd.getSeconds();
        if (m <= 9) m = "0" + m;
        if (d <= 9) d = "0" + d;
        if (hh <= 9) hh = "0" + hh;
        if (mm <= 9) mm = "0" + mm;
        if (ss <= 9) ss = "0" + ss;
        var date = y + "-" + m + "-" + d + " " + hh + ":" + mm + ":" + ss;
        return date;
      }

      this.form.irrigationTime = parseInt(this.intervalDurationL == '' ? 0 : this.intervalDurationL) * 60 + parseInt(this.intervalDurationR == '' ? 0 : this.intervalDurationR)
      this.timeLeft = this.form.startDate
      this.timeRight = time(this.form.startDate, this.form.irrigationTime * 60 * 1000)
      time(this.form.startDate, parseInt(this.form.irrigationTime) * 60 * 60 * 1000)
      console.log(this.form.irrigationTime)
      let left = -1;
      let right = 0;
      this.TableList.map(item => {
        left += 1;
        right += 1;
        // console.log(left, right)
        // console.log(time(this.form.startDate, parseInt(this.form.intervalDuration) * 60 * 60 * 1000))
        item.remarks = time(this.form.startDate, (parseInt(this.form.irrigationTime) * left) * 60 * 1000)
        item.reserveTwo = time(this.form.startDate, (parseInt(this.form.irrigationTime) * right) * 60 * 1000)
      })
    },
    // 执行顺序
    sequenceBtn(value) {
      this.sequence = value
    },
    setModal1Visible(modal1Visible) {
      this.modal1Visible = modal1Visible
    },
    startOnChange(date, string) {
      this.form.startDate = string
      this.startEnd()
    },
    // 保存
    onSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.form.groupNames = this.TableList.map(item => {
            return item.deviceNames
          }).join(',')
          if (this.title == '编辑灌溉计划') {
            if (this.form.irrigationTime == 0 || this.form.irrigationTime == '') {
              this.$message.success("每组灌溉时长不能为空");
              return false
            }
            this.form.id = this.id
            editList(this.form).then(res => {
              this.modal2Visible = false
              this.$parent.dataList(1, 10, '', '')
              this.$message.success(res.message);
              this.resetForm()
            }).catch(err => {

            })
            return false
          }
          add(this.form).then(res => {
            if (this.form.irrigationTime == 0 || this.form.irrigationTime == '') {
              this.$message.success("每组灌溉时长不能为空");
              return false
            }
            this.modal2Visible = false
            this.$parent.dataList(1, 10, '', '')
            this.$message.success(res.message);
            this.resetForm()
          }).catch(err => {

          })
        } else {
          return false
        }
      })
    },
    handleChange(value) {
      let options = [];
      let size = value.length;
      for (let i = 0; i < size; i++) {
        let a = {};
        a.id = value[i];
        options.push(a);
      }
      this.listDel = options
      this.form.groupIds = value.join(',')

      function getArrDifSameValue(arr1, arr2) {
        var result = [];
        for (var i = 0; i < arr2.length; i++) {
          var obj = arr2[i];
          var id = obj.id;
          var isExist = false;
          for (var j = 0; j < arr1.length; j++) {
            var aj = arr1[j];
            var n = aj.id;
            if (n == id) {
              isExist = true;
              break;
            }
          }
          if (isExist) {
            result.push(obj);
          }
        }
        return result;
      }

      this.TableList = getArrDifSameValue(options, this.irrigationGroups)
      console.log(this.TableList)
      this.startEnd()
    },
    delSelect(value) {
      var arrRemoveJson = function (arr, attr, value) {
        if (!arr || arr.length == 0) {
          return ""
        }
        let newArr = arr.filter(function (item, index) {
          return item[attr] != value
        })
        return newArr
      }
      this.TableList = arrRemoveJson(this.TableList, 'id', value)
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
      this.intervalDurationL = 0
      this.intervalDurationR = 0
    },
    // 轮灌组数据获取
    irrigationGroup() {
      irrigationGroupLists().then(res => {
        this.irrigationGroups = res.result
        this.spin = false
      }).catch(err => {
        this.spin = false
      })
    },
    editList(id) {
      this.id = id
      edit(id).then(res => {
        this.group = res.result.groupIds.split(',')
        this.TableList = res.result.eList
        this.irrigationGroup()
        this.spin = false
        this.form = res.result
        console.log(res)

        function ChangeHourMinutestr(str) {
          if (str !== "0" && str !== "" && str !== null) {
            return ((Math.floor(str / 60)).toString().length < 2 ? "0" + (Math.floor(str / 60)).toString() :
              (Math.floor(str / 60)).toString()) + ":" + ((str % 60).toString().length < 2 ? "0" + (str % 60).toString() : (str % 60).toString());
          } else {
            return "";
          }
        }

        this.intervalDurationL = parseInt(ChangeHourMinutestr(res.result.irrigationTime).split(":")[0])
        this.intervalDurationR = parseInt(ChangeHourMinutestr(res.result.irrigationTime).split(":")[1])
      }).catch(err => {
        this.spin = false
      })
    }
  }
}
</script>
<style scoped>
.spin-content {
  background-color: #e6f7ff;
}
</style>
